<?php

class AdminUser extends EMongoDocument
{
    public $username;
    public $password;
    public $ctime;
    public $mtime;
    
    public function getCollectionName()
    {
        return 'admin_user';
    }

    /**
	 * Returns the static model of the specified AR class.
	 * @return TimeZone the static model class
	 */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function indexes()
    {
        return array(
            'username'=>array('key'=>array('username'=>EMongoCriteria::SORT_ASC), 'unique'=>true),
        );
    }
    
    public function behaviors()
	{
        return array(
            'authUser'=>array(
                'class'=>'backend.modules.auth.components.AuthUserBehavior',
            )
        );
	}
    
    /**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
            array('username, password', 'required'),
            array('username', 'common.extensions.YiiMongoDbSuite.extra.EMongoUniqueValidator'),
            array('ctime, mtime', 'safe'),
		);
	}

    public function beforeSave()
    {
        if(parent::beforeSave())
        {
            $this->password = self::encryptPassword($this->password);
            return true;
        }
        else
            return false;
    }
    
    /**
     * encrypt the password
     * @param string $password
     * @return string
     */
    static public function encryptPassword($password)
    {
        return md5($password);
    }
    
    /**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'_id' => 'ID',
			'username' => 'Username',
			'password' => 'Password',
			'ctime' => 'Created Time',
			'mtime' => 'modified Time',
		);
	}
    
    /**
     * update the user's password
     * @param string $newPassword
     * @return boolean 
     */
    public function updatePassword($newPassword)
    {
        if( ! is_string($newPassword))
        {
            $this->addError('password', 'the new password must be a string');
            return false;
        }
        
        $newPassword = trim($newPassword);
        
        //@todo the length of password sure be validated with a CFormModel
        if(5 >= strlen($newPassword))
        {
            $this->addError('password', 'the new password must be longer than 5 chars');
            return false;
        }
        
        if($this->getIsNewRecord())
            $this->password = $newPassword;
        else
            $this->password = self::encryptPassword($newPassword);
        
        return $this->save();
    }
}